package org.luxor.common.netty.jdk.aio.client;

import org.luxor.common.netty.jdk.aio.client.handler.ConnectCompletionHandler;
import org.luxor.common.netty.jdk.nio.server.MultiplexerTimeServerHandler;
import org.luxor.commons.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeClientHandler implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(MultiplexerTimeServerHandler.class);
    private String host;
    private int port;
    private CountDownLatch latch;
    private AsynchronousSocketChannel clientAsyncSocketChannel;

    /**
     * 初始化多路复用器，绑定监听端口
     */
    public AsyncTimeClientHandler(String host, int port) {
        this.host = StringUtils.isBlank(host) ? "127.0.0.1" : host;
        this.port = port;
        try {
            // 1、打开AsynchronousSocketChannel，绑定客户端本地地址(可选，默认系统会随机分配一个可用的本地地址)
            clientAsyncSocketChannel = AsynchronousSocketChannel.open();
            System.out.println("The time client is start in host:" + host + "/ port: " + port);
        } catch (Exception e) {
            log.error("创建异步非阻塞IO客户端网络通道.失败!", e);
            System.exit(1);
        }
    }

    @Override
    public void run() {
        // 初始化CountDownLatch对象,确保在完成一组正在执行的操作之前，允许当前的线程一直阻塞
        this.latch = new CountDownLatch(1);
        // 请求连接服务端
        this.clientAsyncSocketChannel.connect(new InetSocketAddress(this.host, this.port), this, new ConnectCompletionHandler());
        try {
            latch.await();
        } catch (InterruptedException e) {
            log.warn("异步非阻塞IO客户端处理器，出现锁异常", e);
        }
        try {
            this.clientAsyncSocketChannel.close();
        } catch (IOException e) {
            log.warn("异步非阻塞IO客户端处理器，关闭通道失败", e);
        }
    }

    public CountDownLatch getLatch() {
        return latch;
    }

    public AsynchronousSocketChannel getClientAsyncSocketChannel() {
        return clientAsyncSocketChannel;
    }
}
